﻿using Web.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Infrastructure.Identity;
using System;
using ApplicationCore.Interfaces;
using Web;
using Microsoft.AspNetCore.Authentication;
using ApplicationCore.Entities;
using Web.Services;
using ApplicationCore.Specifications;
using System.Linq;

namespace Web.Controllers
{

	public class HomeController : Controller
	{
		private readonly IChatMsgService _chatMsgService;
		private readonly IRoomService _roomService;
		private readonly UserManager<ApplicationUser> _userManager;
		private readonly SignInManager<ApplicationUser> _signInManager;
		private readonly RoleManager<ApplicationRole> _roleManager;

		public HomeController(UserManager<ApplicationUser> userManager,
			SignInManager<ApplicationUser> signInManager, IRoomService roomService, IChatMsgService chatMsgService)
		{
			_userManager = userManager;
			_signInManager = signInManager;
			this._roomService = roomService;
			this._chatMsgService = chatMsgService;

		}


		public IActionResult Index()
		{


			return View();
		}

		/// <summary>
		/// 根据房间号创建游客
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public async Task<IActionResult> CreateGuest(int id)
		{

			var room = await _roomService.Get(id);

			if (!User.Identity.IsAuthenticated)//如果没登录，自动创建游客账户
			{
				var user = new ApplicationUser
				{
					UserName = id + DateTime.Now.ToString("FFFFF"),
					RoomId = id,
					Note = "游客自动创建"
				};
				user.Email = user.UserName + "@" + Request.Host.Host;

				var result = await _userManager.CreateAsync(user, "Aa.111111");
				if (!result.Succeeded)
					throw new Exception("创建游客用户失败！");

				result = await _userManager.AddToRoleAsync(user, "游客");
				if (result.Succeeded)
				{
					await _signInManager.SignInAsync(user, isPersistent: false);

					return Redirect("/Home/" + nameof(Room) + "?no=" + room.RoomNo);
				}

			}

			return Redirect("/Home/" + nameof(Error) + "?no=" + room.RoomNo);

		}

		public async Task<IActionResult> Room(string no)
		{
			if (string.IsNullOrEmpty(no))
				no = Request.Query["no"];

			if (string.IsNullOrWhiteSpace(no))
				return RedirectToAction(nameof(Error));


			var room = await _roomService.Get(no);

			room.ChatMsgs = await _chatMsgService.GetItemsByRoomId(room.Id, DateTime.Now);

			if (room == null) return RedirectToAction(nameof(Error));

			if (!User.Identity.IsAuthenticated)
			{
				return Redirect("/Home/" + nameof(CreateGuest) + "/" + room.Id);
			}
			//判断用户的roomid是否匹配
			var user = await _userManager.FindByNameAsync(User.Identity.Name);
			if (user.RoomId != room.Id)
			{
				await _signInManager.SignOutAsync();
				return Redirect("/Home/" + nameof(CreateGuest) + "/" + room.Id);

			}
			ViewBag.UserInfo = new UserViewModel
			{ 
				UserName = user.UserName,
				RoomId = user.RoomId,
				RoleName = (await _userManager.GetRolesAsync(user)).ToList()
			};



			return View(room);

		}

		public IActionResult Login()
		{
			return View();
		}

		[HttpPost]
		[AllowAnonymous]
		[ValidateAntiForgeryToken]
		[AddLoginLogWithFactory(LoginOptType = OptType.SignIn)]
		public async Task<JsonResult> Login(LoginViewModel model)
		{
			var re = await _signInManager.PasswordSignInAsync(model.Name, model.Password, model.RememberMe, false);
			return new JsonResult(re);

		}


		/// <summary>
		/// 财经日历弹窗
		/// </summary>
		/// <returns></returns>
		public async Task<IActionResult> FinanceCalendar()
		{
			return View();
		}

		public async Task<IActionResult> Error()
		{
			return View();
		}

	}
}
